package com.psg.service.impl;

import com.psg.dao.CarDao;
import com.psg.dao.ProduceDao;
import com.psg.exception.RuleDoesNotMeetException;
import com.psg.pojo.Car;
import com.psg.pojo.Produce;
import com.psg.service.CarService;
import com.psg.vo.CarProduceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Transactional
public class CarServiceImpl implements CarService {
    @Autowired
    private CarDao carDao;
    @Autowired
    private ProduceDao produceDao;
    @Override
    public Long getCarIdAccount(Integer cId) {
        return carDao.getCarIdAccount(cId);
    }

    @Override
    public List<Car> findMyCar(Integer cId) {
        return carDao.findMyCar(cId);
    }

    @Override
    public Long updateCar(Integer uId, Integer pId, Integer count) {
        Car car=carDao.hasCar(uId,pId);
        if (car!=null){
            car.setAccount(car.getAccount()+count);
            carDao.updateById(car);
        }else {
            Produce produce = produceDao.selectById(pId);
            Car newCar = new Car();
            newCar.setAccount(count);
            newCar.setUserId(uId);
            newCar.setPId(pId);
            newCar.setPrice(produce.getPrice());
            newCar.setProductName(produce.getShortName());
            carDao.insert(newCar);
        }
        return getCarIdAccount(uId);
    }

    @Override
    public void deleteCar(Integer id) {
        carDao.deleteById(id);
    }

    @Override
    public List<CarProduceVo> findMyCarProduces(int userId) {
        return carDao.queryMyCarProducesList(userId);
    }

    @Override
    public void deleteCarProduce(int id) {
        carDao.deleteCarProduceById(id);
    }

    @Override
    public void updateCarProduceAccount(int id, int i) {
        Car car = carDao.queryById(id);
        if (null == car) throw new RuleDoesNotMeetException("要修改的购物车商品不存在！");
        if (car.getAccount().compareTo(1) <= 0&&i<=0) throw new RuleDoesNotMeetException("购物车商品数量至少为1");
        car.setAccount(car.getAccount()+i);
        carDao.updateById(car);
    }

    @Override
    public Double computeTotalPriceByIds(int[] ids) {
        List<Car> carList  = carDao.queryByIds(ids);
        AtomicReference<Double> totalPrice = new AtomicReference<>(0d);
        carList.forEach(car -> {
            totalPrice.updateAndGet(v -> v + car.getPrice() * car.getAccount());
        });
        return Double.valueOf(new DecimalFormat("#.00").format(totalPrice.get()));
    }

}
